import 'dart:io';

import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';
class BluetoothHelper {

  static Future<void> startScan() async {
    // Android 12+
    if (await Permission.bluetoothScan.request().isGranted &&
        await Permission.bluetoothConnect.request().isGranted &&
        await Permission.location.request().isGranted) {

      FlutterBluePlus.startScan(timeout: Duration(seconds: 5));

      FlutterBluePlus.scanResults.listen((results) {
        for (var r in results) {
          print('${r.device.name} - ${r.rssi}');
        }
      });

    } else {
      print('蓝牙或位置权限未授予');
    }
  }
  // 检查并请求蓝牙权限
  static Future<bool> checkBluetoothPermissions() async {
    // 检查蓝牙权限
    PermissionStatus bluetoothStatus = await Permission.bluetooth.request();
    // 检查定位权限（Android 10+）
    PermissionStatus locationStatus = await Permission.location.request();

    if (bluetoothStatus.isGranted && locationStatus.isGranted) {
      return true; // 蓝牙和定位权限都被授权
    } else {
      return false; // 蓝牙或定位权限被拒绝
    }
  }




  // 打开蓝牙设置页面
  static Future<void> openBluetoothSettings() async {
    if(Platform.isAndroid){
      await FlutterBluePlus.turnOn();
    }

  }

  // 获取当前蓝牙权限状态
  static Future<String> getBluetoothPermissionStatus() async {
    PermissionStatus bluetoothStatus = await Permission.bluetooth.status;
    if (bluetoothStatus.isGranted) {
      return 'Bluetooth permission granted';
    } else if (bluetoothStatus.isDenied) {
      return 'Bluetooth permission denied';
    } else if (bluetoothStatus.isPermanentlyDenied) {
      return 'Bluetooth permission permanently denied';
    } else {
      return 'Bluetooth permission unknown';
    }
  }

  // 获取当前位置权限状态（用于Android 10及以上）
  static Future<String> getLocationPermissionStatus() async {
    PermissionStatus locationStatus = await Permission.location.status;
    if (locationStatus.isGranted) {
      return 'Location permission granted';
    } else if (locationStatus.isDenied) {
      return 'Location permission denied';
    } else if (locationStatus.isPermanentlyDenied) {
      return 'Location permission permanently denied';
    } else {
      return 'Location permission unknown';
    }
  }
}
